export default class miniRequest {
	baseUrl = '';
	option = {
		url: '',
		data: '',
		header: {},
		method: 'GET',
		timeout: 5000,

	};
	headsOptions = [];
	responseIntercept= (res) => {};
	requestIntercept= (options) => {};

	//校验是否完整url
	isCompleteURL = (url) => {
		return /(http|https):\/\/([\w.]+\/?)\S*/.test(url);
	};

	// 拦截器
	interceptors = {
		request(options) {
			this.requestIntercept(options)
		},
		response(res) {
			this.responseIntercept(res)
		}
	};


	setBaseUrl = (url) => {
		this.baseUrl = url
	};
	setHeader = (key = '', value = '') => {
		if (!key || !value) {
			throw 'setHeader参数错误';
			return
		}
		this.headsOptions.push([key, value])
	};

	setResponseIntercept = (fn) => {
		this.responseIntercept = fn;
	};

	setRequestIntercept = (fn) => {
		this.requestIntercept = fn;
	};

	useRequest = (options = {}) => {
		return new Promise((resolve, reject) => {
			this.option.url = this.isCompleteURL(options.url) ? options.url :
				`${this.baseUrl}${options.url}`;
			this.option.data = options.data ?? '';
			this.option.method = options.method || this.option.method;
			this.option.timeout = options.timeout || this.option.timeout;
			// 添加请求头
			this.headsOptions.forEach((head) => {
				let headObject = {};
				headObject[head[0]] = head[1];
				this.option.header = {
					...this.option.header,
					...headObject
				}
			});
			// 合并参数
			const optionKey = Object.keys(this.option);
			const optionsKey = Object.keys(options);
			optionsKey.forEach((key) => {
				// 如果当前key不在默认配置中就需要添加
				if (!optionKey.includes(key)) {
					Reflect.set(this.option, key, options[key]);
				}
			});
			this.interceptors.request.call(this, this.option);
			this.option.complete = (res) => {
				//执行响应拦截器 
				this.interceptors.response.call(this, res)
				resolve(res)
			}
			// console.log(this.option)
			uni.request(this.option)
		});

	};
};
